/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
  ToolbarAndroid,
  Dimensions,
  BackHandler,
  Platform,
  ListView,
  StatusBar,
  DeviceEventEmitter
} from 'react-native';
import {CachedImageBackground} from "react-native-img-cache";
import Common from '../../component/common';
import ScreenUtils from '../../component/ScreenUtils';
import ToolbarComponent from '../../component/ToolbarComponent';

import SubscriptionItem from '../me/part/subscriptionItem';
import InfoItem from '../me/part/infoItem';
import VarietyItem from '../me/part/varietyItem';

import Loading from '../../component/loading';
import LoadError from '../../component/loadError';

const wechat=require('../../images/wechat.png');
const weibo=require('../../images/weibo.png');
const web=require('../../images/newspaper.png');

import BriefIntroduction from '../specialColumn/briefIntroduction';

const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 20;


const totalWidth = Dimensions.get('window').width;
const HEADER_HEIGHT = totalWidth*0.112;

let totalList = [];  

export default class subscription extends Component {
  constructor(props) {
    super(props);
    this.state = {
    	dataSource: new ListView.DataSource({
        	rowHasChanged: (row1, row2) => row1 !== row2,
      	}),
      	loading: true,
		success: false,
		userToken: loginInfo.userToken,
    };
    this.fetchData = this.fetchData.bind(this);
  }
  
  componentWillMount() {  
    if (Platform.OS === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }  
  }  
  componentWillUnmount() { 
  	this.timer && clearTimeout(this.timer); 
    this.columnDetails.remove();
    if (Platform.OS === 'android') {  
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }  
  } 
  componentDidMount(){
  	this.fetchData();
    this.columnDetails = DeviceEventEmitter.addListener('successPay',()=>{
      this.fetchData();
    });
  }
  fetchData(){
		let formData = new FormData();
	  	formData.append("userToken",this.state.userToken);
	    Common.fetchData("post", "/userCenter/unionPay/list", formData, (responseData) => {
		    this.setState({
				dataSource:this.state.dataSource.cloneWithRows( responseData.listResult),
				dataLength:responseData.listResult.length,
				loading: false,
				success: true,
			})
	    },() => {
	      this.setState({
			loading: false,
			success: false,
			errorMessage: "请求失败",
		  })
	    },() => {
		    this.setState({
				loading: false,
				success: false,
				errorMessage: "网络错误",
			});
	    });	  
  }
  
  
 renderSubscription(data,sectionID,rowID) {
    return (
	      <TouchableHighlight underlayColor="#fafafa" delayPressIn={100}  style ={styles.subItemContainer} onPress={() => Common.onForward(this, BriefIntroduction,"", data.id,"","no","Normal","")}>
      		<View style ={{flex:1,flexDirection:"row"}}>
            <View style={styles.subItemConWrap}>
      				<View style={styles.userAbout}>
      					<View style={styles.userImgWrap}>
      						{
      							data.userPic ?
      								<Image 
      									style={styles.userImg} 
      									source={{uri: data.userPic}} 
      								/> :
      								<Image style={styles.userImg} source = {require('../../images/me/User.png')}/>
      						}	
      					</View>
      					<View style={styles.userInfo}>
      						<Text style={styles.userName}>{data.userName}</Text>
      						<Text 
      							style={styles.userRanking}
      							numberOfLines = {2}
      						>
      							{data.userRank}
      						</Text>
      					</View>
      				</View>
      				<View style={styles.subItemAbout}>
      					<Text style={styles.subItemTitle} numberOfLines = {2}>{data.specialColumnTitle}</Text>
      					<View style={styles.subMagazine}>
      						<Text style={styles.subMagazineText} >
      							<Text style={{paddingRight:ScreenUtils.scaleSize(20),}}>更新到第{data.columnNumber}期/共{data.totalColumnNumber}期</Text>
      							
      							{
      								data.updatePeriodInfo ? <Text style={{marginLeft:30,}}>&nbsp;&nbsp;&nbsp;&nbsp;{data.updatePeriodInfo} </Text> :null
      							}
      						</Text>
      					</View>
      				</View>
      			</View>
      			<View style={styles.subItemImgCon}>
      				<View style={styles.subItemImgWrap}>
      					{
      						data.specialColumnPic1 ?
      								<CachedImageBackground
      									style={styles.subItemcoverImg} 
      									source={{uri: data.specialColumnPic1 }}
      								/>
      							 : <View style={[styles.subItemImgWrap,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
      					}
      					{
      						data.columnNumber < data.totalColumnNumber?
      						<View style={styles.scStatusWrap}>
      							<Image style={styles.scStatusImage} source = {require('../../images/flag-gengxin.png')}/>
      							<Text style={styles.scStatusText}>更新</Text>
      						</View> :null
      					}
      					
      				</View>
      			</View>
          </View>
	      </TouchableHighlight>
    );
  }
  
  render() {
    return (
      <View style ={styles.subscriptionContainer}>
  	    <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>我的订阅</Text>
          </View>
        </ToolbarComponent>
		{
      		this.state.loading ?
				<Loading/>
					: (
						this.state.success ?
							<ScrollView
					        keyboardDismissMode = "on-drag"
					    	  showsVerticalScrollIndicator ={false}
					    	  keyboardShouldPersistTaps="always"
							     horizontal = {false}
                   removeClippedSubviews={ Platform.OS === 'android' ? true : false}
					      	>
							{
								this.state.dataLength == 0 ?
								<View style={styles.noCollection}>
									<Text>您还没有订阅过任何专栏</Text>
								</View> :
								<View style={styles.subscriptionItem}>
							      	<ListView
										  dataSource={this.state.dataSource}
									    renderRow={this.renderSubscription.bind(this)}
									    enableEmptySections={true}
									    scrollRenderAheadDistance={500}
										  removeClippedSubviews={ Platform.OS === 'android' ? true : false}
									   />
						      	</View>
							}
					      	</ScrollView>
						    : <LoadError reload={this.fetchData} reason={this.state.errorMessage}/>
					)      		
      }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  subscriptionContainer:{
    flex: 1,
  	backgroundColor:"#f6f6f6",
  	flexDirection:"column",
  },
  subscriptionItem:{
  	marginTop:ScreenUtils.scaleSize(14),
  	paddingBottom:ScreenUtils.scaleSize(14),
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: ScreenUtils.scaleSize(40),
  },
  subItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"row",
  	height:ScreenUtils.scaleSize(330),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  	marginBottom:ScreenUtils.scaleSize(14),
  },
  subItemConWrap:{
  	flex:1,
  	flexDirection:"column",
  	marginBottom:ScreenUtils.scaleSize(42),
  	marginLeft:ScreenUtils.scaleSize(30),
  	paddingLeft:ScreenUtils.scaleSize(10),
  	paddingRight:ScreenUtils.scaleSize(10),
  },
  userAbout:{
  	height:ScreenUtils.scaleSize(130),
  	borderBottomWidth:1,
  	borderColor:"#d2d2d2",
  	flexDirection:"row",
  	alignItems:"center",
  },
  userImgWrap:{
  	width:ScreenUtils.scaleSize(76),
  	height:ScreenUtils.scaleSize(76),
  },
  userImg:{
  	width:ScreenUtils.scaleSize(76),
  	height:ScreenUtils.scaleSize(76),
  	borderRadius:ScreenUtils.scaleSize(76)/2,
  },
  userInfo:{
  	flex:1,
  	paddingLeft:ScreenUtils.scaleSize(26),
  	flexDirection:"column",
  	justifyContent:"center",
  },
  userName:{
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#000",
  },
  userRanking:{
  	fontSize:ScreenUtils.scaleSize(18),
  	color:"#939393",
  	lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  },
  subItemAbout:{
  	flex:1,
  	flexDirection:"column",
  	justifyContent:"space-around",
  },
  subItemTitle:{
  	color:"#000",
  	fontSize:ScreenUtils.scaleSize(30),
  	paddingTop:ScreenUtils.scaleSize(5),
  },
  subMagazine:{
  	flexDirection:"row",
  },
  subMagazineText:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#939393",
  	marginBottom:ScreenUtils.scaleSize(5),
  	lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  },
  subItemImgCon:{
  	width:ScreenUtils.scaleSize(225),
  	justifyContent:"center",
  	alignItems:"center",
  },
  subItemImgWrap:{
  	width:ScreenUtils.scaleSize(183),
  	height:ScreenUtils.scaleSize(246),
  	position:"relative",
    justifyContent:"center",
    alignItems:"center",
  },
  scStatusWrap:{
  	position:"absolute",
  	top:0,
  	right:0,
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(54),
  },
  scStatusImage:{
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(54),
  },
  scStatusText:{
  	width:ScreenUtils.scaleSize(54),
  	fontSize:ScreenUtils.scaleSize(16),
  	textAlign:"center",
  	position:"relative",
  	top:-(ScreenUtils.scaleSize(54)/2),
  	marginTop:-ScreenUtils.scaleSize(16),
  	color:"#fff",
    backgroundColor: 'transparent'
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  subItemcoverImg:{
  	width:ScreenUtils.scaleSize(183),
  	height:ScreenUtils.scaleSize(246),
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingBottom:ScreenUtils.scaleSize(14),
  },
  Item:{
  	marginTop:ScreenUtils.scaleSize(10),
  	borderTopWidth:1,
  	borderColor:"#ededed",
  },
  showMore:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor:'#fff',
  	borderBottomWidth:1,
  	borderColor:'#ebebeb',
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(14),
  	marginBottom:ScreenUtils.scaleSize(14),
  },
  noCollection:{
  	flex:1,
  	height:Dimensions.get('window').height-HEADER_HEIGHT-STATUS_BAR_HEIGHT,
  	justifyContent: 'center',
    alignItems: 'center',
  }
});